﻿using AutoMapper;
using Comain.Orders;
using Common;
using IRepository;
using IService;
using IService.Rempos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service
{
    public class OrderService : IOrderService
    {
        private readonly IBaseRespository<T_Order> odal;
        private readonly IMapper mapper;

        public OrderService(IBaseRespository<T_Order> odal,IMapper mapper)
        {
            this.odal = odal;
            this.mapper = mapper;
        }
        /// <summary>
        /// 更新订单状态
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <returns>返回更新后的数据行数</returns>
        public async Task<int> ChangeOrder(string orderId)
        {
            try
            {
                var info = await odal.GetItemById(x => x.Order_SnowId == orderId);
                info.Order_State = OrderStateEnum.已结算;
                return await odal.UpdateAsync(info);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 显示订单
        /// </summary>
        /// <returns>返回订单数据</returns>
        public PageComm<List<OrderDTO>> show(string? name, string? orderFrom, DateTime? orderIntime, int index, int size)
        {
            IQueryable<T_Order> orders = odal.GetList();
            //预订人
            if (!string.IsNullOrEmpty(name))
            {
                orders = orders.Where(x => x.Order_UserName.Contains(name));
            }
            //订单来源
            if (!string.IsNullOrEmpty(orderFrom))
            {
                orders = orders.Where(x => x.Order_From == orderFrom);
            }
            //日期
            if (orderIntime != null)
            {
                //属性：获取日期时间类型参数的日期部分（年月日）
                orders = orders.Where(x => x.Order_InTime.Date == Convert.ToDateTime(orderIntime).AddDays(1).Date);
            }
            //计算总数
            int totalCount = orders.Count();
            //计算总页数
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / size);
            //完成分页 跳过：Skip() 取：Take()
            orders = orders.Skip((index - 1) * size).Take(size);


            //通过AutoMapper进行类型转换 T_Order=>OrderDTO
            List<OrderDTO> orderDTOs = mapper.Map<List<OrderDTO>>(orders);
            return new PageComm<List<OrderDTO>>()
            {
                Comm_MyProprty = orderDTOs,
                Comm_PageCount = pageCount,
                Comm_TotalCount = totalCount,
            };
        }
    }
}
